<template>
    <div class="adminRole">
        <el-form ref="formRef" :inline="true" :model="form" class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]">
            <el-form-item :label="t('jobRegion.regionName') + ':'" prop="name">
                <el-input v-model="form.name" :placeholder="t('jobRegion.enterTheNameOfTheRegion')" clearable
                    class="!w-[200px]" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="useRenderIcon(Search)" :loading="loading" @click="newSearch">
                    {{ t('jobRegion.search') }}
                </el-button>
                <el-button :icon="useRenderIcon(Refresh)" @click="newReset(formRef)">
                    {{ t('jobRegion.reset') }}
                </el-button>
            </el-form-item>
        </el-form>

        <div class="center_bg">
            <PureTableBar :title="t('jobRegion.regionalManagement')" :columns="columns" @refresh="newSearch"
                style="width: 410px;" v-if="tableHtml">
                <template #buttons>
                    <el-dropdown placement="left" trigger="click" @command="handleCheckboxChange"
                        style="margin-right: 5px;">
                        <el-button type="primary" plain :icon="useRenderIcon(EpArrowDown)" size="small">
                            {{ filterTitle }}
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-for="item in jobTypeList" :key="item.value" :command="item">
                                    {{ item.label }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-button type="success" size="small" :icon="useRenderIcon(AddFill)" @click="addCross">
                        {{ t('jobRegion.locale') }}
                    </el-button>
                </template>
                <template v-slot="{ size, dynamicColumns }">
                    <pure-table ref="tableRef" adaptive :default-expand-all="true" align-whole="center" size="small"
                        border showOverflowTooltip table-layout="auto" :loading="loading" :data="dataList"
                        :columns="dynamicColumns" :pagination="pagination" :paginationSmall="true" :header-cell-style="{
                            background: 'var(--el-fill-color-light)',
                            color: 'var(--el-text-color-primary)'
                        }" @page-size-change="handleSizeChange" @page-current-change="handleCurrentChange">
                        <template #expand="{ row }">
                            <ul class="table_expand">
                                <li class="station">
                                    <div class="title">
                                        <span>{{ t('jobRegion.passingVehicles') }}：</span>
                                    </div>
                                    <div>
                                        <el-tag size="small" type="success" v-for="v in row.agvNameList" :key="v"
                                            style="margin:5px 5px;">
                                            {{ v }}
                                        </el-tag>
                                    </div>
                                </li>
                            </ul>
                        </template>
                        <template #operation="{ row }">
                            <el-button class="reset-margin" link type="primary" size="small" @click="crossUp(row.id)">
                                {{ t('jobRegion.edit') }}
                            </el-button>
                            <el-button class="reset-margin" link type="danger" size="small" style="margin-left: 0px;"
                                @click="deleteCross(row)">
                                {{ t('jobRegion.delete') }}
                            </el-button>
                        </template>
                    </pure-table>
                </template>
            </PureTableBar>

            <!-- 设置任务区域地图 -->
            <div class="mapDraw mt-2">
                <div class="mapCross">
                    <div class="mapCorrd">
                        <p>x:{{ mouseCorrd.x }},y:{{ mouseCorrd.y }}</p>
                    </div>
                    <div id="canvasMap" ref="map"></div>
                </div>
            </div>
        </div>

        <!-- 抽屉 -->
        <el-drawer v-model="pureMap.crossSwitch"
            :title="isUpdate ? t('jobRegion.modifyTaskArea') : t('jobRegion.addTaskArea')" direction="ltr" size="400px"
            :close-on-click-modal="true" :modal="false" modal-class="modalCross">
            <el-alert :title="t('jobRegion.text_1')" type="warning" center :closable="false"
                style="margin-bottom:20px" />
            <!-- <crossForm :formInline="formInline" :isUpdate="isUpdate" ></crossForm> -->
            <crossForm :isUpdate="isUpdate" ref="crossRef"></crossForm>
        </el-drawer>

    </div>
</template>

<script lang='ts' setup>
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDept } from "./utils/hook";
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { getCross } from '@/utils/api/dispatch/cross'
import mapCross from "./components/mapCross.vue";
import {
    initKonvaStage,
    mouseCorrd,
    stage,
    layer
} from "@/views/home/components/dxfMap";
import { readFile } from '@/views/home/components/readFile'
import { useMapStoreHook } from "@/store/modules/map";
import crossForm from './crossForm.vue'
import { websock } from '@/utils/webScoket'
import { ElMessageBox } from 'element-plus'
import { message } from "@/utils/message";
import { Van, Guide, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { taskareaList, taskareaAdd, taskareaUpdate, taskareaDel, getTaskarea } from '@/utils/api/dispatch/jobRegion'
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
const { locale } = useTranslationLang();
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { crossColor } from '@/views/home/components/dxfMap'

// iconify-icons
import AddFill from "@iconify-icons/ri/add-circle-line";
import EditPen from "@iconify-icons/ep/edit-pen";
import outlineDelete from '@iconify-icons/ic/outline-delete';
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import EpArrowDown from "@iconify-icons/ep/arrow-down-bold";

const formRef = ref();
const map = ref()
const pureMap = useMapStoreHook()
var isUpdate = ref(false)
const crossRef = ref(null)
var isContract = ref(false)

const tableHtml = ref(true);

watch(() => locale.value, (val) => {
    tableHtml.value = false
    nextTick(() => {
        tableReloading()
        filterTitle.value = t('jobRegion.all')
        jobTypeList.value = [
            { label: t('jobRegion.all'), value: 0 },
            { label: t('jobRegion.taskArea'), value: 1 },
            { label: t('jobRegion.floor'), value: 2 },
            { label: t('jobRegion.rotatingCargoArea'), value: 3 },
            { label: t('jobRegion.noRotationAreaWithoutLoad'), value: 4 },
            { label: t('jobRegion.turnAroundArea'), value: 5 },
            { label: t('jobRegion.chargingArea'), value: 6 },
            { label: t('jobRegion.prohibitedAccessArea'), value: 7 },
        ]
        tableHtml.value = true
    })
})

const jobTypeList: any = ref([
    { label: t('jobRegion.all'), value: 0 },
    { label: t('jobRegion.taskArea'), value: 1 },
    { label: t('jobRegion.floor'), value: 2 },
    { label: t('jobRegion.rotatingCargoArea'), value: 3 },
    { label: t('jobRegion.noRotationAreaWithoutLoad'), value: 4 },
    { label: t('jobRegion.turnAroundArea'), value: 5 },
    { label: t('jobRegion.chargingArea'), value: 6 },
    { label: t('jobRegion.prohibitedAccessArea'), value: 7 },
])

const itemDeep = ref()
function hideNonType1Crosses(type) {
    // 查找所有 name 以 "job-" 开头的组
    const jobCrosses = layer.find(node =>
        node.getClassName() === 'Group' &&
        node.name().startsWith('job-')
    );

    if (type === 0) {
        jobCrosses.forEach(group => {
            group.show()
        })
        return
    }

    // 遍历所有找到的组
    jobCrosses.forEach(group => {
        group.show()
        // 获取组的 type 属性
        const groupType = group.attrs.type;

        // 如果 type 不等于 1，则隐藏该组
        if (groupType !== type) {
            group.hide();
        }
    });

    // 重绘画布以应用更改
    layer.draw();
}
const filterTitle = ref(t('jobRegion.all'))
const handleCheckboxChange = (item) => {
    itemDeep.value = item
    filterTitle.value = item.label
    filterData(item.value)
    hideNonType1Crosses(item.value)
}

const colorType = ref()
// 监听抽屉开关，当抽屉关闭时刷新列表数据
watch(() => pureMap.crossSwitch, (newValue) => {
    if (!newValue) {
        const color = crossColor.get(colorType.value)

        pureMap.targetCross.children?.forEach(v => {
            if (v.name() === 'circle') {
                v.fill(color)
            } else {
                v.stroke(color)
            }
        })
        onSearch().then(() => {
            handleCheckboxChange(itemDeep.value)
        })
    }
})

watch(() => isUpdate.value, (newValue) => {
    pureMap.$patch({
        addOrEdit: newValue
    })
})

const newSearch = () => {
    onSearch().then(() => {
        handleCheckboxChange(itemDeep.value)
    })
}

const newReset = (formRef) => {
    resetForm(formRef)
    handleCheckboxChange({ label: '全部', value: 0 })
}

// 车辆移除任务区域
function agvClose(row, agvid) {
    ElMessageBox.confirm(
        `是否确认将${agvid}移出${row.name}任务区域?`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }
    ).then(() => {
        websock.send(JSON.stringify({ type: '移出任务区域', data: row.id, agvid }));
        message(`提交成功`, { type: "success" });
    }).catch(() => { })
}

// 任务区域新增
function addCross() {
    pureMap.operateDrawer(true)
    isUpdate.value = false
    crossRef.value?.resetForm(crossRef.value.getRef())
}

// 任务区域编辑
function crossUp(id: number) {
    pureMap.$patch({
        crossSwitch: true
    })
    isUpdate.value = true
    nextTick(() => {
        crossRef.value.crossUpdate(id)
    })
}

// 删除任务区域
function deleteCross(row) {
    ElMessageBox.confirm(
        `是否确认删除名称为${row.name}的数据项?`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
        }
    ).then(() => {
        taskareaDel(row.id).then(res => {
            if (res.Code === 0) {
                pureMap.stageKonva.find(`.job-${row.name}`)[0].destroy()
                message(`您删除了名称为${row.name}的这条数据`, { type: "success" });
                onSearch();
            }
        })
    }).catch(() => { })
}

async function infoMap() {
    const data = await readFile();
    initKonvaStage("canvasMap", map, data, true);

    // 监听舞台（stage）上的双击事件
    stage.on("dblclick", function (e) {
        // 检查crossSwitch标志，如果为true则直接返回，不执行后续操作
        if (pureMap.crossSwitch) return false;
        // console.log(e.target);

        const id = e.target.parent?.id();
        if (id) {
            // 将获取到的id转换为数字类型，并调用crossUp函数进行处理
            crossUp(Number(id));
            colorType.value = e.target.parent.attrs.type
        } else {
            addCross();
        }
    });
}

onMounted(async () => {
    infoMap()
})

onUnmounted(() => {
    pureMap.clearCross()
})

const {
    columns,
    loading,
    dataList,
    handleDelete,
    form,
    onSearch,
    resetForm,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    agvCrossSwitch,
    crossSearch,
    expandOpen,
    filterData,
    tableReloading
} = useDept();

</script>

<style lang="scss" scoped>
.search-form {
    :deep(.el-form-item) {
        margin-bottom: 12px;
    }
}

.table_expand {
    padding-left: 15px;
}

.center_bg {
    display: flex;
    justify-content: space-between;
    height: 100%;
}

.mapDraw {
    width: calc(100% - 420px);
    background: white;

    .mapCross {
        position: relative;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, rgba(62, 61, 61, 0.4) 2%, transparent 0%) 0 0, linear-gradient(180deg, transparent 99%, rgba(62, 61, 61, 0.4) 1%) 0 0;
        background-size: 50px 50px;
        background-color: #001529;
    }

    #canvasMap {
        width: 100%;
        height: 100%;
    }
}

.lookAgv {
    height: 23px;
    margin-left: 15px;
    vertical-align: bottom;

    &:hover {
        cursor: pointer;
    }
}

.station {
    display: flex;
    align-items: center;

    .title {}

    .el-icon:hover {
        cursor: pointer;
    }

    .stationArr {
        width: 380px;
        height: 30px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}
</style>